package user

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"time"
	"zhuandan/utils"

	"github.com/gin-gonic/gin"
	"net/http"
	"zhuandan/data_source"
	"zhuandan/models"
)

const (
	appidapp     = "wx70dbc7ba3b88147c"
	appsecretapp = "d71b79a7eef22edceff86073d1ca5230"
)

func UserLoginapp(ctx *gin.Context) {
	json1 := KDRespBody{}
	ctx.ShouldBind(&json1)
	code := json1.Code
	open := Accesstoken4(code)
	//fmt.Println(open)
	//return
	openid := open.Openid
	unionid := open.Unionid

	data1 := Accesstoken1(openid, open.AccessToken)
	if data1.Openid == "" {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    300,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "授权失败",
		})
		return
	}
	//fmt.Println(data1)
	reqip := ctx.ClientIP()
	var user1 models.User
	data_source.Db.Where("unionid = ?", data1.Unionid).First(&user1)

	if user1.ID > 0 {
		upuser1 := models.User{
			LoginTime: time.Now().Unix(),
			LoginIp:   reqip,
			AppOpenid: openid,
		}
		data_source.Db.Where("unionid = ?", data1.Unionid).Updates(upuser1)
	} else {
		var user models.User
		data_source.Db.Where("app_openid = ?", openid).First(&user)
		data := Appaccountuser(unionid)
		var guanlian int64
		guanlian = 2
		if data.User.AccountId == "" {
			guanlian = 1
		}
		var price float64
		if data.User.Money != "" {
			price = utils.StrToFloat64(data.User.Money)
		}

		if user.ID > 0 {
			upuser := models.User{
				LoginTime: time.Now().Unix(),
				LoginIp:   reqip,
				LoginNum:  user.LoginNum + 1,
				Price:     price,
			}
			data_source.Db.Where("app_openid = ?", openid).Updates(upuser)
			if price == 0 {
				data_source.Db.Model(&models.User{}).Where("app_openid = ?", openid).Update("price", 0)
			}
		} else {

			nickname := data1.Nickname
			if data.User.Nickname != "" {
				nickname = data.User.Nickname
			}

			logo := data1.Headimgurl
			if data.User.Headimgurl != "" {
				logo = data.User.Headimgurl
			}

			var phone string
			if data.User.Mobile != "" {
				phone = data.User.Mobile
			}

			adduser := models.User{
				LoginTime:  time.Now().Unix(),
				LoginIp:    reqip,
				AppOpenid:  openid,
				CreateTime: time.Now().Unix(),
				LoginNum:   1,
				Logo:       logo,
				Nickname:   nickname,
				Status:     1,
				Unionid:    data1.Unionid,
				Phone:      phone,
				Price:      price,
				Guanlian:   guanlian,
				Province:   data1.Province,
				Dakefu:     1,
				Ifbuy:      1,
			}
			data_source.Db.Create(&adduser)
		}
	}

	var userinfo models.User
	data_source.Db.Where("app_openid = ?", openid).First(&userinfo)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    userinfo,
		"msg":     "ok",
	})
	return
}

type Responseuser struct {
	Nickname   string `json:"nickname"`
	Headimgurl string `json:"headimgurl"`
	Openid     string `json:"openid"`
	Province   string `json:"province"`
	Unionid    string `json:"unionid"`
}

func Accesstoken1(openid, access_token string) (data Responseuser) {

	resp, err := http.Get("https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN")
	//fmt.Println(code)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := Responseuser{}
	fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}

func Accesstoken4(code string) (data ResponseOpenid) {
	resp, err := http.Get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appidapp + "&secret=" + appsecretapp + "&code=" + code + "&grant_type=authorization_code")
	//fmt.Println(code)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := ResponseOpenid{}
	//fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}
